package com.jfs.utils;

import com.thoughtworks.xstream.XStream;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

/**
 * @Description xml对象转换工具
 * @E-mail cwm3412638@163.com
 * @Author cwm
 * @Date 2022/7/22
 */
public class XstreamUtil {
    /**
     * xml 转换对象
     *
     * @param clz
     * @param xml
     * @param <T>
     * @return
     */
    public static <T> T toBean(Class<T> clz, String xml) {
        XStream xStream = new XStream();
        xStream.allowTypesByRegExp(new String[]{".*"});
        xStream.processAnnotations(clz);
        xStream.autodetectAnnotations(true);
        Object o = xStream.fromXML(xml);
        if (clz.isInstance(o)) {
            return clz.cast(o);
        }
        return null;
    }

    /**
     * 转换xml字符数据为bean
     * @param clz
     * @param content
     * @return
     * @param <T>
     * @throws UnsupportedEncodingException
     */
    public static <T> T toBean(Class<T> clz, byte[] content) throws UnsupportedEncodingException {
        XStream xStream = new XStream();
        xStream.allowTypesByRegExp(new String[]{".*"});
        xStream.processAnnotations(clz);
        xStream.autodetectAnnotations(true);
        Object o = xStream.fromXML(new String(content, StandardCharsets.UTF_8));
        if (clz.isInstance(o)) {
            return clz.cast(o);
        }
        return null;
    }

    /**
     * Java bean转xml
     *
     * @param clz
     * @param object
     * @return
     */
    public static String toXml(Class<?> clz, Object object) {
        XStream xStream = new XStream();
        xStream.allowTypesByRegExp(new String[]{".*"});
        xStream.processAnnotations(clz);
        xStream.autodetectAnnotations(true);
        return xStream.toXML(object);
    }
}
